package com.pactera.madp.cp.handler.sync.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.FtpConfig;
import com.pactera.madp.common.core.util.SpringContextHolder;
import com.pactera.madp.cp.api.dto.sync.SyncDTO;
import com.pactera.madp.cp.api.entity.sync.SyncStateEntity;
import com.pactera.madp.cp.common.annotations.SyncType;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.enums.sync.FinaServiceEnum;
import com.pactera.madp.cp.common.enums.sync.SyncTypeEnum;
import com.pactera.madp.cp.common.util.sync.SFTPUtils;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.PrdSftpConfig;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.handler.sync.SyncTypeHandler;
import com.pactera.madp.cp.service.sync.template.SyncBusinessService;
import com.pactera.madp.cp.service.sync.template.SyncItemService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.Executor;

@Slf4j
@Component
@SyncType(SyncTypeEnum.FINA)
public class FinaSyncHandler implements SyncTypeHandler {

    @Override
    @SneakyThrows
    public Boolean handler(SyncDTO dto) {
        // 设置前一天日期
        String yesterday = DateUtil.format(DateUtil.offsetDay(new Date(), -1), Constants.DATE_FORMAT);

        Executor executor = SpringContextHolder.getBean(Constants.EXECUTOR_PROCESS_NAME);
        FinaServiceEnum[] finaEnums = FinaServiceEnum.values();
        for (FinaServiceEnum finaEnum : finaEnums) {
            executor.execute(() -> {
                String fileDate = null;
                // 文件生成检测
                if (!checkFile(finaEnum.getSubType(), fileDate)) {
                    if (!checkFile(finaEnum.getSubType(), yesterday)) {
                        log.error("{}{}", finaEnum.getSubType(), "同步文件未生成完毕");
                        return;
                    }
                    fileDate = yesterday;
                }
                // 执行日志信息初始化
                SyncStateEntity syncStateEntity = new SyncStateEntity();
                syncStateEntity.setSyncType(SyncTypeEnum.FINA.getCode());
                syncStateEntity.setSyncSubType(finaEnum.getSubType());
                syncStateEntity.setFileDate(fileDate);
                SyncStateContext.set(syncStateEntity);
                try {
                    // 执行任务
                    ((SyncItemService)SpringContextHolder.getBean(finaEnum.getServiceType())).handler();
                    // 同步数据
                    if (finaEnum.getBusinessServiceType() == null) {
                        return;
                    }
                    SyncBusinessService syncBusinessService =
                            (SyncBusinessService) SpringContextHolder.getBean(finaEnum.getBusinessServiceType());
                    if (ObjectUtil.isNotNull(syncBusinessService)) {
                        syncBusinessService.syncBusiness();
                    }
                } finally {
                    SyncStateContext.remove();
                    // 记录执行日志
                    if (syncStateEntity.isSaveLog()) {
                        log.debug("{}{}", finaEnum.getSubType(), "记录任务执行日志");
                        syncStateEntity.insert();
                        log.debug("{}{}", finaEnum.getSubType(), "日志记录成功");
                    }
                }
            });
        }
        return Boolean.TRUE;
    }

    private boolean checkFile(String subType, String fileDate) {
        log.debug("FINA信息：check");
        String okFile = "";
        if (StrUtil.equals(FinaServiceEnum.PRD.getSubType(), subType)) {
            okFile = Constants.FN_PRD_OK;
        } else if (StrUtil.equals(FinaServiceEnum.STD_DATA.getSubType(), subType)) {
            okFile = Constants.FN_STD_DATA_OK;
        } else if (StrUtil.equals(FinaServiceEnum.CYCLE_SET.getSubType(), subType)) {
            okFile = Constants.FN_CYCLE_SET_OK;
        } else if (StrUtil.equals(FinaServiceEnum.ANNUALIZED_RATE.getSubType(), subType)) {
            okFile = Constants.FN_ANNUALIZED_RATE_OK;
        }

        // ok文件路径设置
        SyncConfig syncConfig = SpringContextHolder.getBean(SyncConfig.class);
        String filepath = SyncUtils.buildFilePath(syncConfig.getPrdFtpFile(), okFile, fileDate);

        PrdSftpConfig sftpConfig = SpringContextHolder.getBean(PrdSftpConfig.class);
        FtpConfig config = new FtpConfig();
        BeanUtil.copyProperties(sftpConfig, config);
        return SFTPUtils.checkFile(config, filepath);
    }
}
